<?php

namespace App\Http\Controllers\backend;
use App\Model\Backend\ItemModel;
use App\Model\Backend\ItemPostsModel;
use App\Model\Backend\ItemTasksModel;
use App\Model\Backend\Member;
use App\Model\Backend\QiyehaoModel;
use App\Model\Backend\RoleModel;
use App\Model\Backend\TaskLogModel;
use App\Model\Backend\TemplatesModel;
use App\Model\Backend\TemplatesStagesTaskModel;
use Illuminate\Http\Request;

use App\Http\Requests;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

use App\Model\Backend\MessageModel;

class ItemsController extends Controller
{


    //项目首页
    public function index(){
        $item=new ItemModel();

        $data=array();
        $appends=array();
        //阶段
        if(!empty($_GET['stage'])){
            $appends['stage']=$_GET['stage'];
            $data['item_stage']=$_GET['stage'];
        }
        //状态
        if(!empty($_GET['status'])){

            if($_GET['status']=="-1"){
                $data['item_status']=0;
            }else{
                $data['item_status']=$_GET['status'];
            }
            $appends['status']=$_GET['status'];
        }

        //类型
        if(!empty($_GET['type'])){
            $appends['type']=$_GET['type'];
            $data['item_type']=$_GET['type'];
        }
        //关键词
        if(!empty($_GET['keyword'])){
            $appends['keyword']=$_GET['keyword'];
        }else{
            $_GET['keyword']="";
        }
        $itemsInfo=$item->where($data)->where('item_name','like',"%".$_GET['keyword']."%")->orderBy('id','desc')->paginate(15);
        $itemsInfo->setPath('backend/items');

        $member=new Member();
        foreach($itemsInfo as $k=>$v){
            $i=$member->find($v['member_id']);
            $itemsInfo[$k]['username']=$i['username'];
        }

        return view('backend.items.index',['itemsInfo'=>$itemsInfo,'appends'=>$appends]);
    }
//新版
    public function indexNew(){


        $member=new Member();
        $item=new ItemModel();
        $task=new ItemTasksModel();
        $appends=array();

        $data=['item_type'=>10];

        //开始时间
        if(!empty($_GET['sort'])){
            $appends['sort']=$_GET['sort'];
           $order=$_GET['sort'];
        }else{
            $appends['sort']="";
            $order="ASC";
        }

        //阶段
        if(!empty($_GET['stage'])){
            $appends['stage']=$_GET['stage'];
            $data['item_stage']=$_GET['stage'];
        }
        //状态
        if(!empty($_GET['status'])){
            $appends['status']=$_GET['status'];
            $data['item_status']=$_GET['status'];
        }
        //地区
        if(!empty($_GET['area'])){
            $appends['area']=$_GET['area'];
        }else{
            $_GET['area']="";
        }
        //时间
        if(!empty($_GET['endDate'])){
            $appends['endDate']=$_GET['endDate'];

        }else{

            $_GET['endDate']=date('Y-m-d H:i:s',time());

        }
        if(!empty($_GET['startDate'])){
            $appends['startDate']=$_GET['startDate'];
        }else{
            $_GET['startDate']="0";
        }
        //面积
        if(!empty($_GET['Minarea'])){
            $appends['Minarea']=$_GET['Minarea'];
        }else{
            $_GET['Minarea']="0";
        }
        if(!empty($_GET['Maxarea'])){
            $appends['Maxarea']=$_GET['Maxarea'];
        }else{
            $_GET['Maxarea']="9999";
        }
        //关键词
        if(!empty($_GET['keyword'])){
            $appends['keyword']=$_GET['keyword'];
        }else{
            $_GET['keyword']="";
        }

        $itemInfo=$item->where($data)->where('item_address','like',"%".$_GET['area']."%")->where('item_name','like',"%".$_GET['keyword']."%")->where('created_at','>=',$_GET['startDate'])->where('created_at','<=',$_GET['endDate'])->where('area','>=',$_GET['Minarea'])->where('area','<=',$_GET['Maxarea'])->orderBy('created_at',$order)->paginate(20);

        $itemInfo->setPath('backend/itemsNew');

        $arr=array();
        //超时
        $timeout=array();
        //混合
        $mixture=array();
        //正常
        $normal=array();
        //完成
        $accomplish=array();

        foreach($itemInfo as $k=>$v){
            $t=0;
            $n=0;
            $arr[$k]['item_info']=$v;

            $arr[$k]['item_info']['shan_username']=$member->find($v['member_id'])['username'];
            $arr[$k]['item_info']['she_username']=$member->find($v['member_id2'])['username'];

            $taskInfo=$task->where(['item_id'=>$v['id']])->get();
            foreach($taskInfo as $i=>$y){
                if($y['task_status']==10&&strtotime($y['task_deadline'])-time()>0||$y['task_status']>=20&&$y['task_status']<30&&strtotime($y['updated_at'])+3600-time()>0){
                    $n++;
                }elseif($y['task_status']==10&&strtotime($y['task_deadline'])-time()<0||$y['task_status']>=20&&$y['task_status']<30&&strtotime($y['updated_at'])+3600-time()<0){
                    $t++;
                }
                $taskInfo[$i]['taskName']=$member->find($y['member_id_task'])['username'];
                $taskInfo[$i]['checkName']=$member->find($y['member_id_check'])['username'];
                $taskInfo[$i]=$y;
            }
            if($t>0&&$n==0){
                $timeout[$k]['task_info']=$taskInfo;
                $timeout[$k]['item_info']=$v;
            }elseif($t>0&&$n>0){
                $mixture[$k]['task_info']=$taskInfo;
                $mixture[$k]['item_info']=$v;
            }elseif($n>0&&$t==0){
                $normal[$k]['task_info']=$taskInfo;
                $normal[$k]['item_info']=$v;
            }else{
                $accomplish[$k]['task_info']=$taskInfo;
                $accomplish[$k]['item_info']=$v;
            }


        }
                $arr=array_merge($timeout,$mixture,$normal,$accomplish);
// dd($itemInfo);

        return view('backend.items.indexNew',['arr'=>$arr,'itemInfo'=>$itemInfo,'appends'=>$appends]);
    }


    //创建项目
    public function create(Request $request){

        if($request->isMethod('post')){
            $files=Input::file('file');

            $files=array_filter($files);

            $item=new ItemModel();
            $item->item_name=Input::get('project_name1').Input::get('project_name2');
            $item->item_address=Input::get('project_province').Input::get('project_city').Input::get('project_address');
            $item->item_describe=Input::get('project_content');
            $item->item_check=Input::get('project_content1');
            $item->item_price=Input::get('project_price');
            $item->bidding_deadline=Input::get('project_expectStartDate');
            $item->item_deadline=Input::get('project_expectFinishDate');
            $item->idea_deadline=Input::get('idea_deadline');
            $item->item_design=Input::get('item_design');
            $item->member_id=Input::get('approve_id1');
            //add 2016-8-29
            $item->area=Input::get('area');
            $item->member_id2=Input::get('approve_id2');
            $dir="uploads/".Input::get('project_name1').Input::get('project_name2')."/前期调研/";
            //创建文件夹

            if(!file_exists(iconv('utf-8', 'gbk',$dir))){
                @mkdir(iconv('utf-8', 'gbk',$dir),0777,true);
            }
            $path="";
            if(!empty($files)) {
                foreach ($files as $k => $v) {
                    $v->move(iconv('utf-8', 'gbk', $dir), iconv('utf-8', 'gbk', $v->getClientOriginalName()));
                    $path .= $v->getClientOriginalName() . ",";
                }

            }
            $item->path=$path;
            //end
            if($item->save()){
                $qiyehao=new QiyehaoModel();
                $qiyehao->text('liusuyang',Input::get('project_name').'   已创建，请审核');
                return redirect('backend/items');
            }
        }else{
            
            $role=new RoleModel();
            $roles=$role->where(['rid'=>23])->get();

            $member=new Member();
            foreach($roles as $k=>$v){
                $roles[$k]['name']=$member->find($v['uid'])['username'];

            }
            return view('backend.items.create',['roles'=>$roles]);
        }

    }
    //项目详情
    public function show($id){

        $item=new ItemModel();

        $itemsInfo=$item->ShowInfo($id);
        $name=Member::find($itemsInfo['member_id'])['username'];

       return view('backend.items.show',['itemsInfo'=>$itemsInfo,'name'=>$name]);
    }
   //编辑项目
    public function edit(Request $request,$id){
        dd($request);
        if($request->isMethod('post')){
            //echo 123;die;
            $item=new ItemModel();
            $items= $item->find($id);
            $items->item_name=Input::get('project_name');
            $items->item_address=Input::get('item_address');
            $items->item_describe=Input::get('project_content');
            $items->item_check=Input::get('project_content1');
            $items->item_price=Input::get('project_price');
            $items->bidding_deadline=Input::get('project_expectStartDate');
            $items->item_deadline=Input::get('project_expectFinishDate');
            $items->idea_deadline=Input::get('idea_deadline');
            $items->item_design=Input::get('item_design');
            $items->member_id=Input::get('approve_id');
            $items->area=Input::get('area');
            $items->save();
            return redirect()->action('backend\ItemsController@show',['id'=>$id]);
        }else{
            $role=new RoleModel();
            $roles=$role->where(['rid'=>23])->get();
            $member=new Member();
            foreach($roles as $k=>$v){
                $roles[$k]['name']=$member->find($v['uid'])['username'];
            }
            $item=new ItemModel();
            $itemsInfo=$item->ShowInfo($id);
            $user=Member::find($itemsInfo['member_id']);
            return view('backend.items.edit',['itemsInfo'=>$itemsInfo,'roles'=>$roles,'user'=>$user]);
        }


    }
    //删除项目
    public function delete($id){

        $item=new ItemModel();
        $tasks=new ItemTasksModel();
        if($item->find($id)->delete()&&$tasks->where(['item_id'=>$id])->delete()){
            return redirect('backend/items');
        }
        return redirect('backend/items');
    }


    //项目审核
    public function check($id){
        if($_POST['action']=="-1"){
            $qiyehao=new QiyehaoModel();
            //业务员userID
            $item=ItemModel::find($id);
            $userID=Member::find($item['member_id'])['wechat'];
            $content=$item['item_name']."（附：".$_POST['content']."）——不通过，请尽快补齐相关资料";
            $posts=new ItemPostsModel();
            $posts->items_id=$id;
            $posts->member_id=session('member')['uid'];
            $posts->username=session('member')['username'];
            $posts->content=$_POST['content'];
            $item->item_status="-1";
           if($item->save()&&$posts->save()) {
               $qiyehao->text($userID,$content);
               echo 1;
           }else{
               echo 0;
           }

        }elseif($_POST['action']=="0"){
            $qiyehao=new QiyehaoModel();
            //审核userID
            $userID="liusuyang";
            $item=ItemModel::find($id);
            $content=$item['item_name']."——相关资料已补齐，请再次审核";
            $item->item_status="0";
            if($item->save()){
                $qiyehao->text($userID,$content);
                echo 1;
            }else{
                echo 0;
            }
        }
    }

    //项目任务详情
    public function task($id){
        $items=new ItemModel();

        $itemInfo=$items->find($id);
        if($itemInfo['item_status']>0){
			$itemTasks=$items->tasksShow($id);
            $roles=$items->userInfo($id);
            $stagesarr=$itemTasks['stages'];
            ksort($stagesarr);
           // dd($stagesarr);
            unset($itemTasks['stages']);
           // dd($itemTasks);
            return view('backend.items.task',['itemTasks'=>$itemTasks,'itemInfo'=>$itemInfo,'roles'=>$roles,'stagesarr'=>$stagesarr]);
        }else{
			
            // if(session('member')['gid'] != 1) abort(403);
			
			$templates=new TemplatesModel();
            $templatesInfo=$templates->templates();
           //dd($templatesInfo);
            return view('backend.items.task_1',['itemInfo'=>$itemInfo,'templatesInfo'=>$templatesInfo]);
        }


    }
    //任务第二步
    public function task_next(Request $request){
        //dd($request);
        $item_name=ItemModel::find($request->get('id'))['item_name'];
        $task=new TemplatesStagesTaskModel();
        $taskInfo=$task->taskInfo($request->get('template_id'));
//dd($taskInfo);
        return view('backend.items.task_2',['template_id'=>$request->get('template_id'),'id'=>$request->get('id'),'taskInfo'=>$taskInfo,'item_name'=>$item_name]);

    }
    //任务保存
    public function task_save(Request $request){
       //dd($request);
        $task_id=$request->get('task_id');
        $task_name=$request->get('task_name');
        $task_level=$request->get('task_level');
        $member_id_task=$request->get('member_id_task');
        $member_id_check=$request->get('member_id_check');
        $id=$request->get('id');
        $task_deadline=$request->get('task_deadline');
        $template_id=$request->get('template_id');
        $stage_id=$request->get('stage_id');
        $type_id=$request->get('type_id');
        $role_id=$request->get('role_id');
        $audit_rank=$request->get('audit_rank');
        // $money=$request->get('money');
        foreach($task_id as $k=>$v){
            $items_tasks=new ItemTasksModel();
            $arr=[
                'task_id'=>$v,
                'task_name'=>$task_name[$k],
                'task_level'=>$task_level[$k],
                'member_id_task'=>$member_id_task[$k],
                'member_id_check'=>$member_id_check[$k],
                'task_deadline'=>$task_deadline[$k],
                'type_id'=>$type_id[$k],
                'role_id'=>$role_id[$k],
                'item_id'=>$id,
                'template_id'=>$template_id,
                'stage_id'=>$stage_id[$k],
                'audit_rank'=>$audit_rank[$k],
                'created_at'=>date('Y-m-d H:i:s',time()),
                'updated_at'=>date('Y-m-d H:i:s',time()),

				// 'money'=>$money[$k]
            ];
            $a[$k]= $items_tasks->insertGetId($arr);
        }

        $userids=array_unique(array_merge($member_id_task,$member_id_check));


        $userids=Member::whereIn('uid',$userids)->get();

        $userIDS="";

        foreach($userids as $v){
            $userIDS .=$v['wechat']."|";
        }
        $items=new ItemModel();
        $templates=TemplatesModel::find($template_id);
        $itemInfo=$items->find($id);
        $userID1=Member::find($itemInfo['member_id'])['wechat'];
        $contents1="您的项目”".$itemInfo['item_name']."”已经开始设计";
        $contents="欢迎加入".$itemInfo['item_name']."项目，请至工作台查看任务";
        $itemInfo->item_status=1;
        $itemInfo->item_type=$templates['project_type_id'];
        $itemInfo->item_stage=1;
        $itemInfo->item_starttime=date('Y-m-d',time());
        $itemInfo->save();
        $qiyehao=new QiyehaoModel();
        $log=new TaskLogModel();
        $task=new ItemTasksModel();
        $b= $task->find($a[0]);
        $task->where(['item_id'=>$b['item_id'],'task_level'=>$b['task_level']])->update(['task_status'=>10,'task_starttime'=>time()]);
        $log->item_task_id=$a[0];
        $log->action="任务开始";
        $log->save();

        //message 表的添加

        $message=new MessageModel();
        $uid=$_POST['member_id_task'][0];
        $img= Member::find($uid)['img'];
        $items_name=ItemModel::find($_POST['id'])['item_name'];
        $message->action="着手任务开始";
        $message->created_at=time();
        $message->uid=$uid;
        $message->deadline=strtotime($_POST["task_deadline"][0]);
        $message->img=$img;
        $message->items_id=$_POST['id'];
        $message->task_id=$_POST['task_id'][0];
        $message->task_name=$_POST['task_name'][0];;
        $message->items_name=$items_name;
        $message->content=$items_name."-".$_POST['task_name'][0]."着手任务开始";
        $message->save();

        //message 表的添加
        $message1=new MessageModel();
        $uid1=$_POST['member_id_check'][0];
        $img= Member::find($uid1)['img'];
        $items_name=ItemModel::find($_POST['id'])['item_name'];
        $message1->action="审核任务开始";
        $message1->created_at=time();
        $message1->uid=$uid1;
        $message1->deadline=strtotime($_POST["task_deadline"][0]);
        $message1->content=$items_name."-".$_POST['task_name'][0]."审核任务开始";
        $message1->img=$img;
        $message1->items_id=$_POST['id'];
        $message1->task_id=$_POST['task_id'][0];
        $message1->task_name=$_POST['task_name'][0];
        $message1->items_name=$items_name;
        $message1->save();



        $userID=Member::find($member_id_task[0])['wechat'];
        $content="【".$itemInfo['item_name']." ".$task_name[0]."需要您的协助，请至工作台查看。】";
        $qiyehao->text($userID, $content);
        $qiyehao->text($userIDS, $contents);
        $qiyehao->text($userID1, $contents1);

        return redirect()->action('backend\ItemsController@task',['id'=>$id]);
    }

    //删除任务
    public function task_delete(){
        $id=$_POST['id'];
        $task=new ItemTasksModel();
        $res=$task->deleteTask($id);
        if($res){
            echo 1;
        }else{
            echo 0;
        }
    }

    //恢复任务
    public function task_back(){
        $id=$_POST['id'];
        $task=new ItemTasksModel();
        $res=$task->backTask($id);
        if($res){
            echo 1;
        }else{
            echo 0;
        }
    }
    //添加子任务
    public function child_task(){
        //dd($_POST);
        $task=new ItemTasksModel();
        $taskInfo=$task->find($_POST['pid']);
        $task->item_id=$taskInfo['item_id'];
        $task->template_id=$taskInfo['template_id'];
        $task->stage_id=$taskInfo['stage_id'];
        $task->task_name=$_POST['child_name'];
        $task->task_level=$taskInfo['task_level'];
        $task->task_status=$taskInfo['task_status'];
        $task->member_id_task=$_POST['child_userid'];
        $task->member_id_check=$taskInfo['member_id_task'];
        $task->task_deadline=str_replace('截止日期','',$_POST['date']);
        $task->fid=$_POST['pid'];
        if($task->save()){
            echo 1;
        }else{
            echo 0;
        }
    }


    // add by tony 20160811
    public function task_edit(Request $request){

        $session = session('member');
		if($session['gid'] != 1) abort(403);
		
		$id   = $request->get('id');
        $type = $request->get('type');

        $task=new ItemTasksModel();
        $b= $task->find($id);

        if($type == 'check_id'){
            $role_ids  = implode(',', $request->get('role_ids'));
            $b->member_id_check = $role_ids;
            $b->save();
            echo 1;
        }elseif($type =='task_id'){
            $role_ids  = implode(',', $request->get('role_ids'));
            $b->member_id_task = $role_ids;
            $b->save();
            echo 1;
        }elseif($type =='time'){
            $date = $request->get('date');
            $b->task_deadline = $date;
            $b->save();
            echo 1;

        }
    }

}
